package com.hery.services;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hery.pojo.alertManager.AlertManagerData;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;

/**
 * AlertManager 告警服务，http 发送 AlertManagerData
 */
@Slf4j
public class AlertManagerService implements ISendService, Serializable {

    private static CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    //private CloseableHttpAsyncClient asyncHttpClient = HttpAsyncClientBuilder.create().build();

    private String uri;

    public AlertManagerService(String amHost, int amPort){
        uri = String.format("http://%s:%d/api/v1/alerts", amHost, amPort);
        // asyncHttpClient.start();
    }

    public void send(AlertManagerData data) {
        JSONArray arr = new JSONArray();
        int statusCode = 0;
        try {
            arr.add(data);
            log.info("uri:{}", uri);
            HttpPost httpPost = new HttpPost(uri);

            StringEntity se = new StringEntity(JSONObject.toJSONString(arr), StandardCharsets.UTF_8);

            se.setContentEncoding("utf8");
            se.setContentType("application/json");
            httpPost.addHeader("Content-type","application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity(se);

            log.debug("http client execute starting ...");
            CloseableHttpResponse response = httpClient.execute(httpPost);
            statusCode = response.getStatusLine().getStatusCode();

            // Future<HttpResponse> execute = asyncHttpClient.execute(httpPost, new Callbak(arr));
            // statusCode = execute.get().getStatusLine().getStatusCode();

            log.info("Code: {}，Send Alert Data Succeed: {}", statusCode, arr.toString());
        }catch (Exception e){
            log.error("Code: {}, Send Alert Data Failed: {}", statusCode, arr.toString());
            e.printStackTrace();
        }
    }

    public void close() throws IOException {
        httpClient.close();
    }

    public static class Callbak implements FutureCallback<HttpResponse> {

        private JSONArray arr;

        private Callbak(JSONArray arr) {
            this.arr = arr;
        }

        @Override
        public void completed(HttpResponse httpResponse) {
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                log.info("Code: {}，Send Alert Data Succeed: {}", statusCode, arr.toString());
            }else{
                log.error("Code: {}，Send Alert Data Succeed: {}", statusCode, arr.toString());
            }

        }

        @Override
        public void failed(Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();

        }

        @Override
        public void cancelled() {
            log.info("Callbak cancelled");
        }


    }

}
